import re
import os
from reportlab.pdfgen import canvas
from reportlab.pdfbase import ttfonts, pdfmetrics
from reportlab.lib.pagesizes import letter

def reformat_sanzijing(input_file, output_file):
    try:
        with open(input_file, 'r', encoding='utf-8') as f_in, \
             open(output_file, 'w', encoding='utf-8') as f_out:
            for line in f_in:
                stripped_line = line.strip()
                if not stripped_line:
                    f_out.write('\n')
                    continue
                parts = stripped_line.split('\u3000')
                parts = [p for p in parts if p]
                if len(parts) == 4:
                    new_line = f"{parts[0]}\u3000{parts[1]}\n{parts[2]}\u3000{parts[3]}\n"
                    f_out.write(new_line)
                else:
                    f_out.write(stripped_line + '\n')
        return True
    except FileNotFoundError:
        print(f"Error: The file '{input_file}' was not found.")
        return False

def draw_paragraph_on_canvas(c, paragraph_lines, font_name):
    if not any(line.strip() for line in paragraph_lines):
        return # Skip empty paragraphs

    width, height = letter
    margin = 40
    line_spacing_ratio = 1.5
    font_size = 150  # Start with a large font size

    # Calculate optimal font size
    while font_size > 6:
        c.setFont(font_name, font_size)
        line_height = font_size * line_spacing_ratio
        total_height = len(paragraph_lines) * line_height
        max_width = max(c.stringWidth(line, font_name, font_size) for line in paragraph_lines)

        if total_height < (height - 2 * margin) and max_width < (width - 2 * margin):
            break
        font_size -= 2

    # Draw the lines
    c.setFont(font_name, font_size)
    line_height = font_size * line_spacing_ratio
    total_content_height = (len(paragraph_lines) - 1) * line_height
    y = (height + total_content_height) / 2

    for line in paragraph_lines:
        text_width = c.stringWidth(line, font_name, font_size)
        x = (width - text_width) / 2
        c.drawString(x, y, line)
        y -= line_height

    c.showPage()

def create_pdf_from_text(text_file, output_pdf_path):
    output_dir = os.path.dirname(output_pdf_path)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    c = canvas.Canvas(output_pdf_path, pagesize=letter)

    font_path = "C:/Windows/Fonts/simsun.ttc"
    font_name = 'SimSun'
    try:
        if os.path.exists(font_path):
            pdfmetrics.registerFont(ttfonts.TTFont(font_name, font_path))
        else:
            print("Default font 'simsun.ttc' not found. Using Helvetica.")
            font_name = "Helvetica"
    except Exception as e:
        print(f"Font loading error: {e}. Using Helvetica.")
        font_name = "Helvetica"

    with open(text_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    paragraphs = content.split('\n\n')

    for paragraph in paragraphs:
        lines = [line.strip() for line in paragraph.split('\n') if line.strip()]
        if lines:
            draw_paragraph_on_canvas(c, lines, font_name)

    c.save()
    print(f"Successfully created {output_pdf_path}")

if __name__ == "__main__":
    # text_input = '三字经.txt'
    zoomed_text_output = '三字经_zoomed.txt'
    pdf_output = os.path.join("pdf_output", "三字经.pdf")

    print("Step 1: Reformatting text file...")
    # if reformat_sanzijing(text_input, zoomed_text_output):
    # print(f"Successfully reformatted to {zoomed_text_output}")
    print("\nStep 2: Creating PDF...")
    create_pdf_from_text(zoomed_text_output, pdf_output)
